<?php

namespace app\api\controller\v1;

use data\extend\Aes;
use data\extend\ErrCode;
use data\extend\H;
use data\extend\wx\WXBizDataCrypt;
use data\service\ActivityService;
use data\service\DaysignService;
use data\service\MoneysService;
use data\service\PicUserService;
use data\service\UserService;
use data\service\RecordsService;
use think\Request;
use app\api\controller\Api;
use app\sns\validate\ValidataCommon;
use Volc\Service\Visual;

class User extends Api
{

    private $activityService = null;
    private $userService = null;
    private $recordsService = null;
    private $daySignService = null;
    private $moneyService = null;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->activityService = new ActivityService();
        $this->userService = new UserService();
        $this->recordsService = new RecordsService();
        $this->daySignService = new DaysignService();
        $this->moneyService = new MoneysService();
    }

    /**
     * 不需要鉴权方法
     * index、save不需要鉴权
     * ['index','save']
     * 所有方法都不需要鉴权
     * [*]
     */
    protected $noAuth = [];
    protected $mustLogin = ['copyCount','getUserInfoIndex','daySign'];

    public function getQuestions(Request $request){
        if($request->isPost()){
            $info = [
                [
                    'id'=>1,
                    'title'=>'如何获得金币？',
                    'aw'=>'目前仅支持每日签到方式获取。'
                ],
//                [
//                    'id'=>2,
//                    'title'=>'xxx',
//                    'aw'=>'xxxxxxxx'
//                ],
//                [
//                    'id'=>3,
//                    'title'=>'tt',
//                    'aw'=>'ttttttt'
//                ],
//                [
//                    'id'=>4,
//                    'title'=>'xvdfsf',
//                    'aw'=>'fsfsfsdfdd'
//                ],
            ];

            return self::returnMsg(ErrCode::$OK,'success',$info);
        }

    }


    public function getUserConfig(Request $request){
        if($request->isPost()){
            $urlArr = [
                'lg_2159173_1569547510_5d8d64f6c69be.jpg',
                'lg_2210751_1569633505_5d8eb4e199e45.jpg',
                'lg_2480922_1574077209_5dd2831924877.jpg',
                'lg_2808795_1582190882_5e4e51221aa89.jpg',
                'lg_2808868_1582183851_5e4e35ab65eca.jpg',
                'lg_3248479_1593510017_5efb0881eabf1.jpg',
                'lg_3257949_1593618489_5efcb039eead1.jpg',
                'lg_3260015_1593683780_5efdaf447eca7.jpg',
                'lg_3342503_1600348419_5f636103f4209.jpg',
                'lg_3363642_1601444931_5f741c43ba7db.jpg',
            ];
            $config = [
                'shareInfo' => [
                    'title'=>'【卡片说说】总有一句说说戳中你的心坎。',
                    'imageUrl'=>CDN_ROOT_WEB.'static/uploads/shares/'.$urlArr[rand(0,9)].IMG_STYLE,
                    'path'=>'/pages/index/main',
                ],
                'category' =>[
//                    [
//                        'id'=>1,
//                        'name' => '获取金币',
//                        'pic' => CDN_ROOT_WEB.'images/coin-ico.png'.IMG_STYLE,
//                        'type' => 'coin',
//                        'path' =>'-'
//                    ]
                ]
            ];
            return self::returnMsg(ErrCode::$OK,'success',$config);
        }

    }

    public function copyCount(Request $request){
        if($request->isPost()){
            ValidataCommon::validateCheck([
                'contentId' => 'require',
                'type' => 'require'
            ], $request->param('')); //参数验证
            $contentId = $request->post('contentId',0);
            $type = $request->post('type','copys');
            //$contentId , $uid , $type
            $this->recordsService->addRecords($contentId,$this->uid,$type == 'copys' ? 1:2);
            $this->userService->fieldInc($this->uid,$type,1);
            return self::returnMsg(ErrCode::$OK,'success',[]);
        }
    }


    public function getUserInfoIndex(Request $request){
        if($request->isPost()){
            if(!$this->uid){
                return self::returnMsg(ErrCode::$UserNoLogin,'user no login',[]);
            }
            $userInfo = $this->getUserInfo($this->uid);
            return self::returnMsg(ErrCode::$OK,'success',$userInfo);
        }
    }
    public function openid(Request $request){
        if($request->isPost()){
            ValidataCommon::validateCheck([
                'avatarUrl' => 'require',
                'code' => 'require',
                'city' => 'require',
                'country' => 'require',
                'gender' => 'require',
                'nickName' => 'require',
                'province' => 'require'
            ], $request->param('')); //参数验证

            $code = $request->post('code',"");
            $nickName = $request->post('nickName',"");
            $country = $request->post('country',"");
            $province = $request->post('province',"");
            $city = $request->post('city',"");
            $avatarUrl = $request->post('avatarUrl',"");
            $gender = $request->post('gender',"");
            $uid = 0;

            //通过code 获取 session_key 、openid
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd90371be5d857d17&secret=8d9969a4e8e5847ed8ef7abb5ca958fa&js_code=".$code."&grant_type=authorization_code";
            $tempData = json_decode(curl_request($url),1);

            if(isset($tempData['openid'])){
                //拿到openid ，去数据库查询是否存在用户信息
                $tmpUserInfo = $this->userService->getUserInfoByOpenid($tempData['openid'],'id');
                if(empty($tmpUserInfo)){
                    $uid = $this->userService->register($tempData['openid'],$nickName,$avatarUrl,$province,$city);
                } else {
                    $uid = $tmpUserInfo['id'];
                    //更新 登录时间

                }
                //通过用户UID去查询用户信息
                $userInfo = $this->getUserInfo($uid);

                return self::returnMsg(ErrCode::$OK,'success',$userInfo);

            } else {
                return self::returnMsg(ErrCode::$IllegalCode,'Illegal CODE');
            }
        }

    }
    public function daySign(Request $request){
        if($request->isPost()){
            $dayTime = date('Y-m-d',time());
            $signScore = 2;
            $daySignInfo = $this->daySignService->getDaySign($this->uid,$dayTime);

            if($daySignInfo) {
                return self::returnMsg(ErrCode::$ExitDaySign,'today error sign');
            }
            $this->daySignService->addDaySign($signScore,$this->uid,$dayTime);
            //插入记录,签到获取的金币，类型为1
            $this->moneyService->addRecords( $signScore,$this->uid,1,'每日签到');
            //累加
            $this->userService->fieldInc($this->uid,'score',$signScore);

            return self::returnMsg(ErrCode::$OK,'签到成功',$this->getUserInfo($this->uid));

        }
    }

    private function getUserInfo($uid){
        //通过用户UID去查询用户信息
        $userInfo = $this->userService->getUserInfoByUid($uid,'*');
        //获取access_token
        $userInfo['token'] = Aes::aesEn($userInfo['id']);
        $userInfo['lastlogin'] = H::time_tran($userInfo['lastlogin']);
        $userInfo['copys'] = $this->recordsService->countCopys($userInfo['id']);
        $userInfo['favs'] = $this->recordsService->countFavs($userInfo['id']);

        return $userInfo;
    }

    public function test(){
        $arr = [
            'title' =>'壹深圳手机动物园玩法规则',
            'content' => [
                "排行榜规则：",
                "累计叠加为宝宝赚取的口粮数，数量越多，名次越靠前。",
                "赚取口粮规则：",
                "通过萌宠领养做任务，分享邀请好友线上逛园和聊聊天等任务赚取萌宠口粮，每个任务成功将加不同数量的口粮。",
                "萌宠领养说明：",
                "选择自己喜爱的动物进行领养（领养后暂时无法更换），为萌宠取名领取成功后，萌宠成长等级为1，成长等级会根据投喂口粮进行提升，提升等级即可获得抽奖机会，大概率获得话费及门票奖励哟。",
                "宠物等级每提升5级可获得一次抽奖机会（升到2级参与首次抽奖），可获奖品一览：",
                "一等奖：深圳野生动物园门票一张",
                "二等奖：50元话费（仅限广东省内所有运营商）",
                "三等奖：30元话费（仅限广东省内所有运营商）",
                "四等奖：4份口粮",
                "五等奖：3份口粮",
                "六等奖：2份口粮",
                "七等奖：1份口粮",
                "获取口粮规则：",
                "评论一次可投喂1份口粮，每天最高可获得3份口粮；",
                "转发一次可投喂2份口粮，每天最高可获得4份口粮；",
                "遥控摄像头一次可投喂3份口粮，每天最高可获得6份口粮；",
                "萌宠升级所需口粮：",
                "1级：领养即为1级",
                "2级：10份 可抽奖一次",
                "3级：20份",
                "4级：30份",
                "5级：40份 可抽奖一次",
                "6级：50份",
                "7级：60份",
                "8级：70份",
                "9级：80份",
                "10级：90份 可抽奖一次",
                "……（以此类推）",
                "遥控摄像头：",
                "点击此游戏手柄图标可自动进入排队队列，出现倒计时时可以控制摄像头放大缩小，左右摆动，每次30秒。",
                "游戏规则最终解释权归广电集团新媒体中心壹深圳所有！",
            ]
        ];
    }

}
